﻿using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using RESTfulExtension;

namespace RESTfulCore
{
    public class RestClientBase<T> where T : class
    {
        private readonly HttpClient _httpClient;

        public RestClientBase()
        {
            _httpClient = HttpClientFactory.ReuseHttpClientFromHttpClientConnectionPool<T>();

            //HttpClientFactory.CreateSingleHttpClient<T>();
            //HttpClientFactory.ReuseHttpClientFromHtppClientConnectionPool<T>(); 
            //HttpClientFactory.CreateHttpClient<T>();
            _httpClient.CancelPendingRequests();
        }

        public Task<string> GetStringAsync(string apiAction, params string[] paramStrings)
        {
            var requestUri = RequestUri(apiAction, paramStrings);

            return _httpClient.GetStringAsync(requestUri);
        }

        public Task<HttpResponseMessage> GetAsync(string invokeAction)
        {
            return _httpClient.GetAsync(invokeAction);
        }

        public Task<HttpResponseMessage> PutAsync(string invokeAction, HttpContent httpContent)
        {
            return _httpClient.PutAsync(invokeAction, httpContent);
        }


        public Task<HttpResponseMessage> PostAsync(string invokeAction, HttpContent httpContent)
        {
            return _httpClient.PostAsync(invokeAction, httpContent);
        }

        public Task<HttpResponseMessage> DeleteAsync(string invokeAction)
        {
            return _httpClient.DeleteAsync(invokeAction);
        }

        public Task<HttpResponseMessage> SendAsync(HttpRequestMessage httpRequestMessage)
        {
            return _httpClient.SendAsync(httpRequestMessage);
        }

        private string RequestUri(string invokeAction, IReadOnlyCollection<string> paramStrings)
        {
            //var requestUri = paramStrings != null && paramStrings.Count > 0
            //    ? $"{invokeAction}/{paramStrings.Aggregate((a, b) => $"{a}/{b}")}"
            //    : invokeAction;

            var requestUri = paramStrings != null && paramStrings.Count > 0
                ? $"{invokeAction}/{paramStrings.Aggregate((a, b) => $"{a}/{b}")}"
                : invokeAction;

            return requestUri;
        }

    }
}